/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jbrowser.gui.history;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 *
 * @author buczko
 */
public class History<T> {

    private Set<HistoryListener> listeners = new HashSet<HistoryListener>();
    private List<T> history = new LinkedList<T>();
    private int index = -1;

    public boolean addHistoryListener(HistoryListener listener) {
        return listeners.add(listener);
    }

    public boolean removeHistoryListener(HistoryListener listener) {
        return listeners.remove(listener);
    }

    public List<T> getHistory() {
        return new ArrayList<T>(history);
    }

    public int getIndex() {
        return index;
    }

    public int indexOf(T item) {
        return history.indexOf(item);
    }

    public List<T> getAvailableBackHistory() {
        if (hasBack()) {
            return new ArrayList<T>(history.subList(0, index));
        } else {
            return null;
        }
    }

    public List<T> getAvailableNextHistory() {
        if (hasNext()) {
            return new ArrayList<T>(history.subList(index + 1, history.size()));
        } else {
            return null;
        }
    }

    public boolean isEmpty() {
        return history.isEmpty();
    }

    public boolean add(T item) {
        if (item.equals(now())) {
            return true;
        } else {
            if (hasNext()) {
                history.subList(index + 1, history.size()).clear();
            }
            index++;
            return history.add(item);
        }
    }

    public T now() {
        if (history.isEmpty()) {
            return null;
        } else {
            return history.get(index);
        }
    }

    public T jump(int index) {
        if (history.isEmpty()) {
            return null;
        } else {
            this.index = index;
            return history.get(index);
        }
    }

    public T back() {
        if (hasBack()) {
            return history.get(--index);
        } else {
            return null;
        }
    }

    public T next() {
        if (hasNext()) {
//            T next = history.get(++index);
//            for(HistoryListener listener : listeners) {
//                listener.onHisoryNext();
//            }
            return history.get(++index);
        } else {
            return null;
        }
    }

    public boolean hasNext() {
        return index < history.size() - 1;
    }

    public boolean hasBack() {
        return index > 0;
    }
}
